<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/24 0024
 * Time: 20:29
 */


include "library/mRedis.php";
include "model/Order.php";

class OrderService {


    private $config,$redis;

    public function __construct()
    {
        $this->config = include "config/config.php";
        $this->redis = mRedis::get_instance($this->config);
    }

    /**
     * BUY
     * @param $uid
     * @param $symbol
     * @param $price
     * @param $vol
     */
    public function long($uid,$symbol,$price,$vol){
        $data = $this->_queueData($uid,$price,$symbol,$vol,Order::LONG_ACTION);
        $this->redis->zAdd(
            $this->_queueKey($symbol,Order::LONG_ACTION),
            $price,
            $data
        );
        $this->pushTaskQueue($data);
    }

    /**
     * @param $uid
     * @param $symbol
     * @param $price
     * @param $vol
     */
    public function short($uid,$symbol,$price,$vol){
        $data = $this->_queueData($uid,$price,$symbol,$vol,Order::SHORT_ACTION);
        $this->redis->zAdd(
            $this->_queueKey($symbol,Order::SHORT_ACTION),
            $price,
            $data
        );
        $this->pushTaskQueue($data);
    }

    /**
     * @param $uid
     * @param $symbol
     * @param $price
     * @param $vol
     */
    public function long_pending($uid,$symbol,$price,$vol){
        $data = $this->_queueData($uid,$price,$symbol,$vol,Order::PENDING_LONG_ACTION);
        $this->redis->zAdd(
            $this->_queueKey($symbol,Order::LONG_ACTION),
            $price,
            $data
        );
        $this->pushTaskQueue($data);
    }

    public function short_pending(){

    }

    /**
     * 格式化序列KEY
     * @param $symbol
     * @param $action
     * @return string
     */
    public function _queueKey($symbol,$action){
        return strtoupper(sprintf("%s-%s-QUEUE",$symbol,$action));
    }

    /**
     * @param $uid
     * @param $price
     * @param $symbol
     * @param $vol
     * @param $action
     * @return string
     */
    public function _queueData($uid,$price,$symbol,$vol,$action){
        $_tmp = array(
            'uid'   => $uid,
            "price" => $price,
            "symbol"=> $symbol,
            "vol"   => $vol,
            "act"   => $action,
            "time"  => time()
        );
        return json_encode($_tmp);
    }

    /**
     * 当前交易信息推送给任务队列，后续worker处理交易和写入数据库
     * @param $data
     */
    public function pushTaskQueue($data){
        $taskListKey = strtoupper(
            sprintf(
                "%s-task-queue",$this->config->company
            )
        );

        $this->redis->lPush($taskListKey,$data);

    }

}

$orderService = new OrderService();

/*
for($i = 1;$i<=10;$i++){
    $orderService->long("vimphen","USDT",$i,1);
}
*/

for($i = 10;$i<=10;$i++){
    $orderService->short("user2","USDT",$i,1);
    sleep($i + 5);
}


